package request

import (
	models2 "appService/src/application/admin/admin/adminModels"
	"appService/src/application/app/appModels"
	"appService/src/authValid"
	"appService/src/authValid/dataAuth"
	"appService/src/authValid/defaultB"
	"appService/src/authValid/userMap"
	"appService/src/global"
	"appService/src/global/paginate"
	"appService/src/libs/crypot"
	"appService/src/libs/httpResult"
	"appService/src/libs/token"
	"appService/src/libs/utils"
	"appService/src/orm"
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/guid"
	"net"
	"path"
	"path/filepath"
	"reflect"
	"strings"
	"time"
	"xorm.io/builder"
	"xorm.io/xorm"
)

type Request struct {
	Request   *ghttp.Request
	Bid       string              // 当前登录账号的 所属单位ID branch表的ID
	LoginUser *appModels.UserInfo // 当前登陆账号
	IsLogin   bool                // 是否登陆
	Params    []byte              // 前端传递过来的参数
	AuthCode  string              //当前访问的路由
	Paginate  *paginate.Paginate  // 分页结构体
	Model     appModels.IModel    //当前操作的模型对象
}

//Init 执行对象收到请求时的初始化方法，在服务接口调用之前被回调执行
func (this *Request) Init(r *ghttp.Request, model appModels.IModel) {
	this.Request = r
	//初始化变量
	this.IsLogin = false
	this.LoginUser = new(appModels.UserInfo)
	this.Paginate = new(paginate.Paginate)
	if model != nil {
		this.Model = model
	}
	// 角色权限验证。
	this.RolesAuthCheck(true)
	// 获取分页参数
	this.Paginate.PageSize = r.GetInt64("page_size", 12)
	this.Paginate.Page = r.GetInt64("page", 1)
}

//FileInit 下载文件时，初始化的方法
func (this *Request) FileInit(r *ghttp.Request) {
	this.Request = r
	//初始化变量
	this.IsLogin = false
	this.LoginUser = new(appModels.UserInfo)
	// 角色权限验证。
	this.RolesAuthCheck(false)
}

//RolesAuthCheck 角色权限验证。
func (this *Request) RolesAuthCheck(isParams bool) {

	//设置当前访问的路由的权限标识
	this.AuthCode = utils.RouteToAuthCode(this.Request.Router.Uri, this.Request.Router.Method)

	// 判断路由是否需要登录
	apiRoute := authValid.AuthCodeGetRoute(this.AuthCode)
	// 当前 api 是否需要验证签名
	isSign := true
	if apiRoute == nil || apiRoute.Id == "" {
		g.Log().Errorf("数据接口不存在")
		this.JsonError("您访问的数据不存在")
	} else {
		if apiRoute.IsSign != 1 {
			isSign = false
		}
		if apiRoute.Visit > dataAuth.PUBLIC {
			//登陆 验证token权限
			this.ValidToken(false)
			// 判断访问权限
			if apiRoute.Visit > dataAuth.LOGIN {
				// 判断是否有访问权限
				if !authValid.UserIsToAuthCode(apiRoute, this.AuthCode, this.LoginUser) {
					this.JsonNoAuthf("您没有 o(╥﹏╥)o┣ %v ┨ 的操作权限，请联系管理员。", apiRoute.Title)
				}
			}
		}
	}

	//设置当前请求的【部门机构】
	this.SetBranch()
	if isParams {
		//获取前端传递过来的参数
		switch {
		case this.Request.Method == "POST" || this.Request.Method == "PUT" || this.Request.Method == "PATCH" || this.Request.Method == "DELETE":
			this.Params = this.Request.GetBody()
			break
		case this.Request.Method == "GET":
			body := this.Request.Header.Get("Body")
			if body != "" {
				var err error
				this.Params, err = base64.StdEncoding.DecodeString(body)
				if err != nil {
					g.Log().Errorf("参数Base64解码失败,错误：" + err.Error())
					this.JsonError("参数解析失败")
				}
			}
			break
		}

		if isSign {
			//判断数据签名是否正确
			this.CheckParamsSign()
		}
	}
}

//ValidToken Authorization token
//ValidToken 验证token令牌 isReturn为真，会返回 true/false, 为假，只会在验证成功的时候返回真
func (this *Request) ValidToken(isReturn bool) bool {
	tokenStr := this.Request.Cookie.Get("Authorization", "")
	if tokenStr == "" {
		tokenStr = this.Request.Header.Get("Authorization")
	}
	if tokenStr == "" {
		if isReturn {
			return false
		} else {
			this.JsonLogin("您还没有登录，请登录")
		}
	}
	//验证token权限
	ok, err := token.CheckToken(tokenStr, func(uid string, userAccount string, loginStr string) {
		if userMap.Exist(uid) {
			this.LoginUser = userMap.Get(uid)
		} else {
			user := new(appModels.Users)
			ok, err := orm.Db.Where(builder.Eq{"uid": uid}).Get(user)
			if err != nil {
				g.Log().Errorf("token验证 —> 查询用户信息错误：%v", err)
				if !isReturn {
					this.JsonError("权限验证失败")
				}
			}
			if !ok {
				userMap.Remove(uid)
				g.Log().Errorf("token验证 —> 用户【UID=%v】不存在", uid)
				if !isReturn {
					this.JsonReLogin("您的令牌已失效，请重新登录")
				}
			}
			account := new(appModels.Account)
			db := orm.Db.Where(builder.Eq{"account": userAccount, "id": user.AccountId})
			ok, err = db.Get(account)
			if err != nil {
				g.Log().Errorf("token验证 —> 查询用户账号信息错误：%v", err)
				if !isReturn {
					this.JsonError("权限验证失败")
				}
			}
			if !ok {
				userMap.Remove(uid)
				if !isReturn {
					this.JsonReLogin("您的令牌已失效，请重新登录")
				}
			}
			branch, err := this.GetDefaultBranch()
			if err != nil {
				g.Log().Errorf("token验证 —> 获取默认部门机构，错误：%v", err)
				if !isReturn {
					this.JsonError("权限验证失败")
				}
			}
			this.LoginUser.Account = *account
			this.LoginUser.User = *user
			this.LoginUser.DefaultBranchId = branch.Id
			branchIds := authValid.GetBranchIDs(this.LoginUser, true)
			this.LoginUser.BranchIds = *branchIds
		}
		if global.SingleLogin {
			if loginStr != this.LoginUser.User.LoginRand {
				userMap.Remove(this.LoginUser.User.Uid)
				if !isReturn {
					this.JsonReLogin("您的令牌已失效，请重新登录")
				}
			}
		}
		this.LoginUser.User.LoginTime = time.Now()
		this.LoginUser.IsLogin = true
		this.IsLogin = true
		userMap.Set(this.LoginUser)
	})
	if err != nil {
		if isReturn {
			return false
		} else {
			this.JsonErrorf("%v", err)
		}
	}
	if !ok {
		if isReturn {
			return false
		} else {
			this.JsonReLogin("您的令牌已失效，请重新登录")
		}
	}
	return true
}

//CheckParamsSign 判断数据签名是否正确
func (this *Request) CheckParamsSign() {
	ok := this.checkParams(this.Request.Header.Get("Sign"), this.Params)
	if !ok {
		this.JsonError("非法参数")
	}
}

//checkParams 验证前端参数是否合法
func (this *Request) checkParams(signs string, RequestBody []byte) bool {
	if signs == "" {
		g.Log().Errorf("签名不存在")
		return false
	}
	signByte, err := base64.StdEncoding.DecodeString(signs)
	if err != nil {
		g.Log().Errorf("解析签名错误：" + err.Error())
		return false
	}
	signs = string(signByte)
	str := strings.Split(signs, ".")
	if len(str) != 2 {
		g.Log().Errorf("签名错误")
		return false
	}
	signTime := str[1]
	encodeStr := crypot.Md5String(signTime) + "." + base64.StdEncoding.EncodeToString(RequestBody) + "." + signTime
	signStr := crypot.Md5String(base64.StdEncoding.EncodeToString([]byte(encodeStr))) + "." + signTime
	return signStr == signs
}

//ParamsAnalyse 解析参数
func (this *Request) ParamsAnalyse(obj interface{}) {
	if len(this.Params) == 0 {
		return
	}
	err := gconv.Struct(this.Params, obj)
	if err != nil {
		g.Log().Errorf("参数解析失败,错误：%v", err)
		this.JsonError("参数解析失败")
	}
}

//SetBranch 如果当前登陆账号没有所属【部门机构】，就设置为默认的
func (this *Request) SetBranch() {
	if this.LoginUser.Account.Bid == "" || this.LoginUser.Account.Bid == "0" {
		branch, err := this.GetDefaultBranch()
		if err == nil {
			this.LoginUser.Account.Bid = branch.Id
		} else {
			this.JsonError("权限验证失败")
		}
	}
}

//GetDefaultBranch 获取默认【部门机构】
func (this *Request) GetDefaultBranch() (*models2.Branch, error) {
	if defaultB.DefaultBranch.Id == "" {
		branch := new(models2.Branch)
		has, err := orm.Db.Where(builder.Eq{"is_default": 1}).Get(branch)
		if err != nil {
			g.Log().Errorf("GetDefaultBranch：—> 获取默认【部门机构】信息，错误：%v", err)
			return nil, err
		}
		if has {
			defaultB.DefaultBranch = *branch
			return branch, nil
		} else {
			return nil, errors.New("GetDefaultBranch：—> 默认【部门机构】不存在")
		}
	} else {
		return &defaultB.DefaultBranch, nil
	}
}

//Guid 获取一个GUID
func (this *Request) Guid() string {
	var (
		address = this.Request.RemoteAddr
		header  = fmt.Sprintf("%v", this.Request.Header)
	)
	return guid.S([]byte(address), []byte(header))
}

//GetDiy 获取一条数据 可自定义 参数 KEY
func (this *Request) GetDiy(key string) {
	this.ParamsAnalyse(this.Model)
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	data := this.Model.Model()
	err := this.Model.GetWhere(db, this.LoginUser, this.Request.GetString(key))
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	ok, err := db.Get(data)
	if err != nil {
		g.Log().Errorf("获取【%v】失败，错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取失败")
	}
	if ok {
		this.JsonSuccess("", data)
	} else {
		this.JsonError("数据不存在")
	}
}

//Get 获取一条数据
func (this *Request) Get() {
	this.GetDiy("id")
}

//AddHandle 添加处理
func (this *Request) AddHandle(success func()) {
	this.ParamsAnalyse(this.Model)
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	err := db.Begin()
	if err != nil {
		g.Log().Errorf("添加【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("添加失败")
	}
	err = this.Model.Init(db, this.Guid(), this.LoginUser)
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	err = this.Model.AddValid()
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	err = this.Model.AddWhere(db, this.LoginUser)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Insert(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			success()
			this.JsonSuccess("添加成功", this.Model)
		} else {
			_ = db.Rollback()
			g.Log().Errorf("添加【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("添加失败")
		}
	} else {
		_ = db.Rollback()
		g.Log().Errorf("添加【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("添加失败")
	}
}

//DeleteHandle 删除处理
func (this *Request) DeleteHandle(success func(ids []string)) {
	p := struct {
		Ids []string `json:"ids"`
	}{}
	this.ParamsAnalyse(this.Model)
	this.ParamsAnalyse(&p)
	if len(p.Ids) == 0 {
		this.JsonError("请选择要删除的数据")
	}
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	err := db.Begin()
	if err != nil {
		g.Log().Errorf("删除【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("删除失败")
	}
	err = this.Model.DeleteWhere(db, this.LoginUser, p.Ids...)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Delete(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			success(p.Ids)
			this.JsonSuccess("删除成功")
		} else {
			_ = db.Rollback()
			g.Log().Errorf("删除【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("删除失败")
		}
	} else {
		_ = db.Rollback()
		g.Log().Errorf("删除【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("删除失败")
	}
}

//EditHandle 修改处理
func (this *Request) EditHandle(success func()) {
	this.ParamsAnalyse(this.Model)
	err := this.Model.EditValid()
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	err = db.Begin()
	if err != nil {
		g.Log().Errorf("修改【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("修改失败")
	}
	err = this.Model.EditWhere(db, this.LoginUser)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Update(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			success()
			this.JsonSuccess("修改成功", this.Model)
		} else {
			_ = db.Rollback()
			g.Log().Errorf("修改【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("修改失败")
		}
	} else {
		_ = db.Rollback()
		g.Log().Errorf("修改【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("修改失败")
	}
}

//Add 添加
func (this *Request) Add() {
	this.AddHandle(func() {})
}

//Delete 删除
func (this *Request) Delete() {
	this.DeleteHandle(func(ids []string) {})
}

//Edit 修改
func (this *Request) Edit() {
	this.EditHandle(func() {})
}

//List 获取列表
func (this *Request) List() {
	this.ParamsAnalyse(this.Model)
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	list := this.Model.Slice()
	err := orm.Find(db, this.Model, list, func(db *xorm.Session) {
		err := this.Model.ListWhere(db, this.LoginUser)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
	})
	if err == nil {
		this.JsonSuccess("", list)
	} else {
		g.Log().Errorf("获取数据【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取数据失败")
	}
}

//ListPaginate 获取列表（分页）
func (this *Request) ListPaginate() {
	this.ParamsAnalyse(this.Model)
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	pageData := &paginate.PaginateData{
		Paginate: this.Paginate,
	}
	err := orm.FindPaginate(db, this.Model, pageData, func(db *xorm.Session) {
		err := this.Model.ListWhere(db, this.LoginUser)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
	}, func(db *xorm.Session) interface{} {
		err := this.Model.PaginateWhere(db, this.LoginUser)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
		return this.Model.Slice()
	})
	if err == nil {
		this.JsonSuccess("", pageData)
	} else {
		g.Log().Errorf("获取数据【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取数据失败")
	}
}

//AddEx 插入数据 handle数组:第一个成功回调，第二个失败回调
func (this *Request) AddEx(init func(db *xorm.Session, guid string) error, addValid func(db *xorm.Session) error, addWhere func(db *xorm.Session) error, handle ...func()) {
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	err := db.Begin()
	if err != nil {
		g.Log().Errorf("添加【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("添加失败")
	}
	this.ParamsAnalyse(this.Model)
	err = init(db, this.Guid())
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	err = addValid(db)
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	err = addWhere(db)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Insert(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			if len(handle) > 0 {
				handle[0]()
			}
			this.JsonSuccess("添加成功", this.Model)
		} else {
			_ = db.Rollback()
			if len(handle) > 1 {
				handle[1]()
			}
			g.Log().Errorf("添加【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("添加失败")
		}
	} else {
		_ = db.Rollback()
		if len(handle) > 1 {
			handle[1]()
		}
		g.Log().Errorf("添加【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("添加失败")
	}
}

//DeleteEx 删除数据 handle数组:第一个成功回调，第二个失败回调
func (this *Request) DeleteEx(deleteWhere func(db *xorm.Session, ids ...string) error, handle ...func()) {
	p := struct {
		Ids []string `json:"ids"`
	}{}
	this.ParamsAnalyse(this.Model)
	this.ParamsAnalyse(&p)
	if len(p.Ids) == 0 {
		this.JsonError("请选择要删除的数据")
	}
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	err := db.Begin()
	if err != nil {
		g.Log().Errorf("删除【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("删除失败")
	}
	err = deleteWhere(db, p.Ids...)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Delete(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			if len(handle) > 0 {
				handle[0]()
			}
			this.JsonSuccess("删除成功")
		} else {
			_ = db.Rollback()
			if len(handle) > 1 {
				handle[1]()
			}
			g.Log().Errorf("删除【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("删除失败")
		}
	} else {
		_ = db.Rollback()
		if len(handle) > 1 {
			handle[1]()
		}
		g.Log().Errorf("删除【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("删除失败")
	}
}

//EditEx 修改 handle数组:第一个成功回调，第二个失败回调
func (this *Request) EditEx(editValid func(db *xorm.Session) error, editWhere func(db *xorm.Session) error, handle ...func()) {
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	this.ParamsAnalyse(this.Model)
	err := editValid(db)
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	err = db.Begin()
	if err != nil {
		g.Log().Errorf("修改【%v】开启事务失败,错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("修改失败")
	}
	err = editWhere(db)
	if err != nil {
		_ = db.Rollback()
		this.JsonErrorf("%v", err)
	}
	_, err = db.Update(this.Model)
	if err == nil {
		err = db.Commit()
		if err == nil {
			if len(handle) > 0 {
				handle[0]()
			}
			this.JsonSuccess("修改成功", this.Model)
		} else {
			_ = db.Rollback()
			if len(handle) > 1 {
				handle[1]()
			}
			g.Log().Errorf("修改【%v】提交事务失败,错误：%v", reflect.TypeOf(this.Model), err)
			this.JsonError("修改失败")
		}
	} else {
		_ = db.Rollback()
		if len(handle) > 1 {
			handle[1]()
		}
		g.Log().Errorf("修改【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("修改失败")
	}
}

//GetEx 获取一条数据
func (this *Request) GetExDiy(key string, getWhere func(db *xorm.Session, condition string) error) {
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	this.ParamsAnalyse(this.Model)
	data := this.Model.Model()
	err := getWhere(db, this.Request.GetString(key, ""))
	if err != nil {
		this.JsonErrorf("%v", err)
	}
	ok, err := db.Get(data)
	if err != nil {
		g.Log().Errorf("获取【%v】失败，错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取失败")
	}
	if ok {
		this.JsonSuccess("", data)
	} else {
		this.JsonError("数据不存在")
	}
}

//GetEx 获取一条数据
func (this *Request) GetEx(getWhere func(db *xorm.Session, condition string) error) {
	this.GetExDiy("id", getWhere)
}

//ListEx 获取列表
func (this *Request) ListEx(getSlice func() (slice interface{}, table interface{}), listWhere func(db *xorm.Session) error) {
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	this.ParamsAnalyse(this.Model)
	list, table := getSlice()
	err := orm.Find(db, table, list, func(db *xorm.Session) {
		err := listWhere(db)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
	})
	if err == nil {
		this.JsonSuccess("", list)
	} else {
		g.Log().Errorf("获取数据【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取数据失败")
	}
}

//ListPaginateEx 获取列表（分页）
func (this *Request) ListPaginateEx(getSlice func() (slice interface{}, table interface{}), countWhere func(db *xorm.Session) error, findWhere func(db *xorm.Session) error) {
	db := orm.Db.NewSession()
	defer func() {
		_ = db.Close()
	}()
	pageData := &paginate.PaginateData{
		Paginate: this.Paginate,
	}
	this.ParamsAnalyse(this.Model)
	slice, table := getSlice()
	err := orm.FindPaginate(db, table, pageData, func(db *xorm.Session) {
		err := countWhere(db)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
	}, func(db *xorm.Session) interface{} {
		err := findWhere(db)
		if err != nil {
			this.JsonErrorf("%v", err)
		}
		return slice
	})
	if err == nil {
		this.JsonSuccessData(pageData)
	} else {
		g.Log().Errorf("获取数据【%v】错误：%v", reflect.TypeOf(this.Model), err)
		this.JsonError("获取数据失败")
	}
}

//GetProxyClientIp 获取 访问客户端(反向代理) IP
func (this *Request) GetProxyClientIp() string {
	xForwardedFor := this.Request.Request.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(this.Request.Request.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(this.Request.Request.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}

//json 标准返回结果数据结构封装。
func (this *Request) json(code int, message string, data ...interface{}) {
	responseData := interface{}(nil)
	dataLen := len(data)
	if dataLen > 0 {
		if dataLen > 1 {
			responseData = data
		} else {
			responseData = data[0]
		}
	}
	err := this.Request.Response.WriteJson(httpResult.JsonData{
		Code:    code,
		Message: message,
		Data:    responseData,
	})
	if err != nil {
		g.Log().Printf("返回Json数据，错误：%v", err)
	}
}

//JsonWrite 返回json数据
func (this *Request) JsonWrite(data []byte) {
	this.Request.Response.Header().Set("Content-Type", "application/json")
	this.Request.Response.Write(data)
	this.Request.ExitAll()
}

//JsonExit 返回JSON数据并退出当前HTTP执行函数。
func (this *Request) JsonExit(code int, msg string, data ...interface{}) {
	this.json(code, msg, data...)
	this.Request.ExitAll()
}

//JsonSuccess 成功 返回JSON数据
func (this *Request) JsonSuccess(msg string, data ...interface{}) {
	this.json(httpResult.SUCCESS, msg, data...)
	this.Request.ExitAll()
}

//JsonSuccessData 成功 返回JSON数据 没有 msg
func (this *Request) JsonSuccessData(data ...interface{}) {
	this.json(httpResult.SUCCESS, "", data...)
	this.Request.ExitAll()
}

//JsonError 错误 返回JSON数据
func (this *Request) JsonError(msg string, data ...interface{}) {
	this.json(httpResult.ERROR, msg, data...)
	this.Request.ExitAll()
}

//JsonErrorf 错误 返回JSON数据
func (this *Request) JsonErrorf(msg string, params ...interface{}) {
	this.json(httpResult.ERROR, fmt.Sprintf(msg, params...), nil)
	this.Request.ExitAll()
}

//JsonLogin 请登陆 返回JSON数据
func (this *Request) JsonLogin(msg string, data ...interface{}) {
	this.json(httpResult.LOGIN, msg, data...)
	this.Request.ExitAll()
}

//JsonReLogin 登录过期，请重新登录 返回JSON数据
func (this *Request) JsonReLogin(msg string, data ...interface{}) {
	this.json(httpResult.RELOGIN, msg, data...)
	this.Request.ExitAll()
}

//JsonNoAuth 没有访问权限 返回JSON数据
func (this *Request) JsonNoAuth(msg string, data ...interface{}) {
	this.json(httpResult.NOAUTH, msg, data...)
	this.Request.ExitAll()
}

//JsonNoAuthf 没有访问权限 返回JSON数据
func (this *Request) JsonNoAuthf(msg string, params ...interface{}) {
	this.json(httpResult.NOAUTH, fmt.Sprintf(msg, params...), nil)
	this.Request.ExitAll()
}

//UploadFile 文件上传 labelName：参数名称 ext:可以上传的后缀名
func (this *Request) UploadFile(labelName string, extM ...map[string]bool) *appModels.Files {
	extMap := map[string]bool(nil)
	if len(extM) > 0 {
		extMap = extM[0]
	} else {
		extMap = global.FileExt
	}
	file := this.Request.GetUploadFile(labelName)
	if file.Size > global.UploadFileSize {
		this.JsonErrorf("上传文件过大，最大为 %.2f MB", global.UploadFileSize/1024/1024)
	}
	exts := filepath.Ext(file.Filename)
	ext := ""
	if len(exts) > 0 {
		ext = exts[1:]
		_, ok := extMap[ext]
		if !ok {
			this.JsonErrorf("不能上传后缀名为 %v 的文件", ext)
		}
	} else {
		this.JsonError("文件类型错误")
	}
	randomName, err := file.Save(global.FileUploadDir, true)
	if err != nil {
		g.Log().Errorf("上传文件失败，错误：%v", err)
		this.JsonError("文件上传失败")
	}
	temFile := new(appModels.Files)
	temFile.Id = this.Guid()
	temFile.FileSign = this.Guid()
	temFile.Bid = this.LoginUser.Account.Bid
	temFile.FileName = file.Filename[:len(file.Filename)-len(ext)-1]
	temFile.FileSize = file.Size
	temFile.FileExt = ext
	temFile.FileUrl = path.Join(global.FilePathDir, randomName)
	temFile.Created = time.Now()
	return temFile
}
